import React, { Component } from 'react';
import { View, Image, ScrollView, Text, TouchableOpacity, FlatList, RefreshControl, ImageBackground } from 'react-native';
import Colors from '../constants/Colors';
import { MyHeader } from '../components/MyHeader';
import { unitWidth, width } from '../constants/AdapterUtil';
import MyListView from '../components/MyListView';
import ScrollableTabView, { ScrollableTabBar, DefaultTabBar } from 'react-native-scrollable-tab-view';
import { DeleteTextView } from '../components/MyTextView';
import EmptyView from '../components/EmptyView';
import RefreshFooter from '../components/RefreshFooter';
import Swiper from 'react-native-swiper';
import { SubmitButton4, SubmitButton5, SMButton, SDButton, AddShoppingCartButton } from '../components/Button';
import NavigationService from '../constants/NavigationService';
import { Rating, AirbnbRating } from 'react-native-elements';
import { RedEnvelopesModal } from '../components/Modal';
import { api_merch, api_goods_get_list, api_member_info_follow, api_member_redpack_showredpack } from '../constants/HttpServices';
import { postFetch } from '../constants/HttpExtension';
import { show } from '../constants/Toast';
import CommonUtil from '../constants/CommonUtil';
import { contactBrowser } from '../constants/Gobrowser';

export default class ServiceProviderDetailScreen extends Component {
    constructor(props) {
        super(props)
        this.merchid = this.props.navigation.getParam('merchid', 0);
        this.state = {
            CarouselList: [],

            list: [],
            info: {},

            redpackInfo: {}
        }
    }

    componentDidMount() {
        if (this.refs.RedEnvelopesModal) {
            // this.refs.RedEnvelopesModal.showModal();
        }
        this.refs.MyListView.onRefresh();
        this.getInfo()
        this.props.navigation.addListener('didFocus', payload => {

        })
    }

    render() {
        return (
            <View style={{ flex: 1, backgroundColor: Colors.colorF7 }}>
                <MyHeader title='公司详情' leftImg={require('../res/ic_arrow_left.png')} leftClick={() => { this.props.navigation.pop() }} />
                <MyListView
                    style={{ marginBottom: 50 * unitWidth }}
                    ref='MyListView'
                    list={this.state.list}
                    numColumns={2}
                    renderItem={this.getItem.bind(this)}
                    getList={this.getData.bind(this)}
                    canLoadMore={true}
                    ListHeaderComponent={
                        <View>
                            <View style={{ alignItems: 'center' }}>
                                {
                                    this.state.CarouselList && this.state.CarouselList.length > 0 ?
                                        <View style={{ width: width, height: 225 * unitWidth }}>
                                            <Swiper style={{ width: width, height: 225 * unitWidth }} loop={true} autoplay={true} dotStyle={{ marginBottom: -20 * unitWidth }} activeDotStyle={{ marginBottom: -20 * unitWidth }}>
                                                {this.getCarouselView()}
                                            </Swiper>
                                        </View> : null
                                }
                                <View style={{ paddingHorizontal: 20 * unitWidth, width: width, backgroundColor: Colors.white }}>
                                    <Text
                                        style={{
                                            color: Colors.black, fontSize: 15,
                                            marginTop: 5 * unitWidth, marginRight: 60 * unitWidth,
                                        }}>{this.state.info.title}</Text>
                                    <TouchableOpacity style={{
                                        alignItems: 'center', position: 'absolute', top: 7 * unitWidth,
                                        right: 15 * unitWidth, flexDirection: 'row'
                                    }} activeOpacity={0.5} onPress={() => {
                                        if (this.state.isfollow == 1) {
                                            CommonUtil.cancelfollow(this.merchid, {
                                                success: (response) => {
                                                    this.getInfo()
                                                },
                                                fail: (response) => {

                                                }
                                            })
                                        } else if (this.state.isfollow == 0) {
                                            CommonUtil.follow(this.merchid, {
                                                success: (response) => {
                                                    this.getInfo()
                                                },
                                                fail: (response) => {

                                                }
                                            })
                                        }
                                    }}>
                                        <Image style={{ width: 18 * unitWidth, height: 16 * unitWidth }} source={this.state.isfollow == 1 ? require('../res/syss_guanzhu.png') : require('../res/syss_guanzhu2.png')} resizeMode='stretch' />
                                        <Text style={{ color: Colors.color66, fontSize: 13, marginLeft: 3 * unitWidth }}>关注</Text>
                                    </TouchableOpacity>
                                    <View style={{ flexDirection: 'row', alignItems: 'center', height: 35 * unitWidth }}>
                                        <Rating
                                            style={{ marginTop: 7 * unitWidth, alignSelf: 'flex-start', }}
                                            readonly={true}
                                            startingValue={this.state.info.score}
                                            imageSize={20}
                                        />
                                        {this.state.info.is_realname > 0 ? <SMButton style={{}} id={this.merchid} /> : null}
                                        {this.state.info.is_realname > 2 ? <SDButton style={{ marginLeft: 5 * unitWidth }} id={this.merchid} /> : null}
                                    </View>
                                    <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                                        <Image style={{ width: 13 * unitWidth, height: 16 * unitWidth }} source={require('../res/syss_dddw.png')} resizeMode='stretch' />
                                        <Text style={{ color: Colors.color99, fontSize: 13, marginLeft: 5 * unitWidth }}>{this.state.info.address ? this.state.info.address : '未知'}</Text>
                                    </View>
                                    <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 10 * unitWidth }}>
                                        <Image style={{ width: 20 * unitWidth, height: 20 * unitWidth }} source={require('../res/fws_sjh.png')} resizeMode='stretch' />
                                        <Text style={{ color: Colors.color99, fontSize: 13, marginLeft: 5 * unitWidth }}>{this.state.info.mobile ? this.state.info.mobile : '未知'}</Text>
                                        <Image style={{ width: 15 * unitWidth, height: 15 * unitWidth, marginLeft: 10 * unitWidth }} source={require('../res/fws_clsj.png')} resizeMode='stretch' />
                                        <Text style={{ color: Colors.color99, fontSize: 13, marginLeft: 5 * unitWidth }}>成立时间：{this.state.info.jointime}</Text>
                                    </View>
                                    <View style={{ flexDirection: 'row', marginVertical: 10 * unitWidth }}>
                                        <Image style={{ width: 14 * unitWidth, height: 14 * unitWidth, marginTop: 2 * unitWidth }} source={require('../res/syss_zyyw.png')} resizeMode='stretch' />
                                        <Text style={{ color: Colors.color66, fontSize: 14, marginLeft: 5 * unitWidth }}>
                                            {'主营业务：' + (this.state.info.salecate ? this.state.info.salecate : '未知') +
                                                '\n接单类型：' + CommonUtil.getOrderTakingType(this.state.info.order_taking_type) +
                                                '      加工方式：' + CommonUtil.getWorkingType(this.state.info.working_type)}
                                        </Text>
                                    </View>
                                </View>
                                <View style={{
                                    backgroundColor: Colors.white, alignItems: 'center', justifyContent: 'center',
                                    marginTop: 5 * unitWidth, height: 40 * unitWidth, flexDirection: 'row', width: width
                                }}>
                                    <Image style={{ width: 18 * unitWidth, height: 15 * unitWidth }} source={require('../res/fws_syspsp.png')} resizeMode='stretch' />
                                    <Text style={{ color: Colors.black, fontSize: 16, marginLeft: 15 * unitWidth }}>所有商品</Text>
                                </View>
                            </View>
                        </View>
                    }
                />
                <View style={{
                    height: 50 * unitWidth, width: width, flexDirection: 'row', alignItems: 'center', justifyContent: 'center',
                    backgroundColor: Colors.white, position: 'absolute', bottom: 0
                }}>
                    <SubmitButton5 text='邀请报价' onPress={() => { this.props.navigation.navigate('ChooseMyDemand', { merchid: this.merchid }) }} />
                </View>
                <RedEnvelopesModal ref='RedEnvelopesModal' redpackInfo={this.state.redpackInfo} />
            </View>
        )
    }

    getCarouselView() {
        let views = []
        for (let i = 0, len = this.state.CarouselList.length; i < len; i++) {
            let item = this.state.CarouselList[i];
            views.push(
                <TouchableOpacity key={i} style={{
                    justifyContent: 'center',
                    alignItems: 'center',
                }} activeOpacity={0.8} onPress={() => {
                    contactBrowser(item.link)
                }}>
                    <Image
                        source={{ uri: item.thumb }}
                        style={{
                            width: width, height: 225 * unitWidth,
                        }}
                        resizeMode='cover' />
                </TouchableOpacity>
            )
        }
        return views;
    }

    getItem({ item, index }) {
        return (
            <View style={{ justifyContent: 'center', alignItems: 'center', width: width / 2, height: 230 * unitWidth }}>
                <TouchableOpacity style={{
                    width: 172 * unitWidth, height: 215 * unitWidth,
                    alignItems: 'center', backgroundColor: Colors.white, borderRadius: 7, paddingHorizontal: 2 * unitWidth
                }} activeOpacity={0.5} onPress={() => {
                    NavigationService.navigate('GoodsDetail', { id: item.id })
                }}>
                    <Image source={{ uri: item.thumb }}
                        style={{ width: 168 * unitWidth, height: 120 * unitWidth }}
                        resizeMode='cover' />
                    <Text style={{ fontWeight: 'bold', color: Colors.black, fontSize: 16, marginVertical: 4 * unitWidth }}>{item.title}</Text>
                    <View style={{ paddingHorizontal: 7 * unitWidth, borderWidth: 0.5, borderColor: Colors.colorRed, borderRadius: 5, alignSelf: 'flex-start' }}>
                        <Text style={{ color: Colors.colorRed, fontSize: 10, }}>线下价格:￥{item.offlineprice}</Text>
                    </View>
                    <View style={{ alignSelf: 'flex-start', marginTop: 5 * unitWidth, flexDirection: 'row', alignItems: 'center', width: 172 * unitWidth }}>
                        <Text style={{ color: Colors.colorRed, fontSize: 17, }}>￥{item.marketprice}</Text>
                        <DeleteTextView text={'￥' + item.productprice} style={{ marginLeft: 3 * unitWidth }} />
                        <AddShoppingCartButton
                            style={{ position: 'absolute', right: 10 * unitWidth, }}
                            id={item.id} />
                    </View>
                </TouchableOpacity>
            </View>
        )
    }

    //获取商品列表
    getData(page) {
        let params = {
            page: page,
            merchid: this.merchid
        }
        postFetch(api_goods_get_list, params, {
            success: (response) => {
                if (page == 1) {
                    this.setState({
                        list: response.result.list,
                    }, () => {
                        this.refs.MyListView.onHasMore();
                    })
                } else {
                    if (response.result.list && response.result.list.length > 0) {
                        this.setState({
                            list: this.state.list.concat(response.result.list),
                        }, () => {
                            this.refs.MyListView.onHasMore();
                        })
                    } else {
                        this.refs.MyListView.onNoMore();
                    }
                }
            },
            fail: (response) => {
                show(response.result.message);
            }
        })
    }

    //获取公司信息
    getInfo() {
        let params = {
            merchid: this.merchid
        }
        postFetch(api_merch, params, {
            success: (response) => {
                this.setState({
                    info: response.result.shopshare,
                    CarouselList: response.result.adv.list,
                    isfollow: response.result.isfollow
                }, () => {
                    if (response.result.redpackid != '0') {
                        this.checkRedPacketInfo(response.result.redpackid)
                    }
                })
            },
            fail: (response) => {
                show(response.result.message);
            }
        })
    }

    //查看红包信息
    checkRedPacketInfo(id) {
        let params = {
            id: id
        }
        postFetch(api_member_redpack_showredpack, params, {
            success: (response) => {
                this.setState({
                    redpackInfo: response.result
                }, () => {
                    this.refs.RedEnvelopesModal.showModal();
                })
            },
            fail: (response) => {
                show(response.result.message);
            }
        })
    }
}